import { RouteRecordRaw } from 'vue-router'

// Webpack特定的上下文导入
const requireContext = require.context('../views', true,  /^(?!.*\/components\/).*\.vue$/)

/**
 * 解析路由路径
 * @param key 模块路径
 * @returns 路由路径
 */
const resolveRoutePath = (key: string): string => {
  const path = key
    .replace('./', '/')
    .replace('.vue', '')
    .replace(/\/index$/, '') // 处理index.vue作为目录默认页
    
  // 处理根路径
  return path || '/'
}

/**
 * 解析路由名称
 * @param path 路由路径
 * @returns 路由名称（驼峰式）
 */
const resolveRouteName = (path: string): string => {
  if (path === '/') return 'Home'
  
  return path
    .split('/')
    .filter(segment => segment)
    .map(segment => 
      segment.charAt(0).toUpperCase() + segment.slice(1)
    )
    .join('')
}

/**
 * 生成路由元信息
 * @param path 路由路径
 * @returns 路由元信息
 */
const resolveRouteMeta = (path: string): Record<string, any> => {
  return {
    title: path === '/' ? '首页' : 
      path.split('/').filter(segment => segment).join('-')
  }
}

/**
 * 自动生成路由配置（Webpack版本）
 * @returns 路由配置数组
 */
export const generateRoutes = (): RouteRecordRaw[] => {
  const routes: RouteRecordRaw[] = []
  
  // 遍历所有匹配的模块
  requireContext.keys().forEach(key => {
    // 解析组件
    const component = requireContext(key).default
    
    // 生成路由信息
    const routePath = resolveRoutePath(key)
    const routeName = resolveRouteName(routePath)
    const routeMeta = resolveRouteMeta(routePath)
    
    // 添加路由记录
    routes.push({
      path: `/map-app${routePath}`,
      name: routeName,
      component: () => Promise.resolve(component), // 转为异步组件
      meta: routeMeta
    })
  })
  
  return routes
}
    